package com.xuecheng.content.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioTemplate {
    //声明MIME类型常量
    public static final String TEXT_HTML="text/html";
    public static final String IMAGE_JPG="image/jpg";

    @Autowired
    private MinioProperties prop;

    private MinioClient minioClient;

    //初始化
    @PostConstruct
    public void init(){
        minioClient=MinioClient
                .builder()
                .credentials(prop.getAccessKey(),prop.getSecretKey())
                .endpoint(prop.getEndpoint())
                .build();
    }
    //文件上传
    public String upload(InputStream inputStream,String filename){
        try {
            //处理上传文件的文件名称
            String filePath="images/"+ DateTime.now().toString("yyyy/MM/dd")+
                    UUID.randomUUID().toString()+"."+ FileUtil.extName(filename);
            //构造上传的参数对象PutObjectArgs
            PutObjectArgs args=PutObjectArgs.builder()
                    .bucket(prop.getBucket())//指定桶
            .contentType(IMAGE_JPG)//指定MIME类型
            .object(filePath)//指定文件名
            .stream(inputStream,inputStream.available(),-1)//指定文件流
            .build();
            //上传
            minioClient.putObject(args);
            //获取文件的访问地址
            String imageUrl=prop.getDomain()+"/"+prop.getBucket()+"/"+filePath;

            //返回
            return imageUrl;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
